using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using CodeFactory.IDAL;

namespace CodeFactory.SqlServer
{
    public class SqlServerAdapter : CodeFactory.IDAL.IDataAdapter
    {
        private IDbHelper dbHelper;
        public event EventHandler ConnectionComplate;
        public event EventHandler GetTableListComplate;
        public event EventHandler GetColumnListComplate;

        public IDbHelper DbHelper
        {
            get { return this.dbHelper; }
            set { this.dbHelper = value; }
        }

        public SqlServerAdapter()
        {
            this.dbHelper = null;
        }

        public SqlServerAdapter(IDbHelper helper)
        {
            this.dbHelper = helper;
        }

        public void ConnectionDatabase()
        {
            this.dbHelper.Open();
            this.dbHelper.Close();
            if (this.ConnectionComplate != null)
                this.ConnectionComplate(new object(), new EventArgs());
        }

        public List<string> GetTableList()
        {
            this.dbHelper.Open();
            IDataReader dr = this.dbHelper.ExecuteDataReader("select * from [sysobjects] where type='U'");
            List<string> tableList = new List<string>();
            while (dr.Read())
            {
                tableList.Add(Convert.ToString(dr[0]));
            }
            this.dbHelper.Close();
            if (this.GetTableListComplate != null)
                this.GetTableListComplate(new object(), new EventArgs());
            return tableList;
        }

        public List<ColumnInfo> GetColumnList(string tableName)
        {
            List<ColumnInfo> columnList = new List<ColumnInfo>();
            ColumnInfo info = null;
            this.dbHelper.Open();
            IDataReader dr = this.dbHelper.ExecuteDataReader(string.Format("Select TOP 1 * From [{0}]", tableName));
            for (int i = 0; i < dr.FieldCount; i++)
            {
                info = new ColumnInfo();
                info.Name = dr.GetName(i);
                info.Type = dr.GetDataTypeName(i);
                info.CodeType = dr.GetFieldType(i);
                columnList.Add(info);
            }
            dr.Close();
            this.dbHelper.Close();
            if (this.GetColumnListComplate != null)
                this.GetColumnListComplate(new object(), new EventArgs());
            return columnList;
        }
    }
}
